<template>
    <div class="ppt-box">
        <div class="top">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>
                    <strong>共用功能</strong>
                </el-breadcrumb-item>
                <el-breadcrumb-item>修改PPT内容</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="c-box">
            <el-alert title="用前小提示" type="success" effect="dark" :closable="false" show-icon>
                <span v-html="tip"></span>
            </el-alert>
            <div class="up-1">
                <el-button type="primary">
                    1、指定文件路径方式
                    <Edit style="width: 1.3em; height: 1.3em; margin-left:8px;" />
                </el-button>
                <el-form
                    ref="formRef"
                    :model="pptDto1"
                    status-icon
                    label-width="240px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="文件所在地址(包括文件名)" prop="sourceFileUrl" 
                        :rules="[
                            {
                                required: true,
                                message: '请输入有效的文件地址',
                                trigger: 'blur',
                            }
                        ]"
                    >
                        <el-input v-model="pptDto1.sourceFileUrl" type="text" autocomplete="on" placeholder="例:D:\\Projects\\docs\\test.ppt"/>
                    </el-form-item>
                    <el-form-item label="要下载的文件地址(不用写文件名)" prop="targetFileUrl"
                        :rules="[
                            {
                                required: true,
                                message: '请输入有效的下载文件地址',
                                trigger: 'blur',
                            }
                        ]"
                    >
                        <el-input v-model="pptDto1.targetFileUrl" type="text" autocomplete="on" placeholder="例:D:\\Projects\\docs\\test123.ppt"/>
                    </el-form-item>
                    <el-form-item label="指定替换的页码" prop="page">
                        <el-input v-model="page" type="text" autocomplete="on" placeholder="指定要替换的页码，从1开始，不填则替换全部，多个页码用英文逗号隔开，例：1,2..."/>
                    </el-form-item>
                    <el-form-item
                        v-for="(domain, index) in dynamicValidateForm.domains"
                        :key="domain.key"
                        :label="'替换文本' + (index+1)"
                        :prop="'domains.' + index + '.value'"
                    >
                        <el-input style="width:30%" v-model="domain.willReplace" placeholder="请输入要替换的文本内容"/> 
                        &emsp; 替换为<span>{{ index + 1 }}</span>：
                        <el-input style="width:30%" v-model="domain.replaced" placeholder="请输入替换后的文本" />
                        &nbsp;
                        <el-button class="mt-2" @click.prevent="removeDomain(domain)" type="danger">删除当前替换</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" @click="submitForm(formRef)">点击提交</el-button>
                        <el-button type="primary" @click="addDomain">新增替换文本对</el-button>
                        <el-button type="warning" @click="resetForm(formRef)">重置内容</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-divider />
            <div class="up-2">
                <el-button type="primary" @click="uploadWayUseNotice">
                    2、上传文件方式(点击查看使用说明)
                    <UploadFilled style="width: 1.3em; height: 1.3em; margin-left: 8px;" />
                </el-button>
                <el-upload
                    ref="upload"
                    class="upload-demo"
                    :http-request="()=>{}"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :before-upload="beforeDocUpload"
                    :auto-upload="false"
                >
                    <template #trigger>
                        <el-button type="warning">选择源文件</el-button>&emsp;
                    </template>
                    <el-button class="ml-3" type="success" @click="submitUpload">
                        点击提交
                    </el-button>
                    <template #tip>
                        <div class="el-upload__tip text-red">
                            每次只能上传1个文件，新文件将会覆盖旧文件
                        </div>
                    </template>
                </el-upload>
            </div>
            <div class="up-3">
                <el-button type="primary" @click="uploadWayUseNotice">
                    3、上传Excel文件(点击查看使用说明)
                    <UploadFilled style="width: 1.3em; height: 1.3em; margin-left: 8px;" />
                </el-button>
            </div>
            <div class="up-4">
                <el-button type="primary" @click="uploadWayUseNotice">
                    4、上传Word文件(点击查看使用说明)
                    <UploadFilled style="width: 1.3em; height: 1.3em; margin-left: 8px;" />
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { $http } from '@/utils/axios';
import { gatewayPrefix, baseDictServer} from '@/utils/commConstance';
import { ElMessage, genFileId ,ElMessageBox } from 'element-plus';
import { reactive, ref } from 'vue';

let tip = ref('当前功能主要为了修改PPT文件内容，目前只支持修改文本框内容，对于修改图片及图片内容后期陆续完善和开放,当前修改内容提供两种方式修改，'+
    '</br>第一：手动从计算机上位置复制文件所在路径(例:D:/Projects/docs/test.ppt或D:\\\\Projects\\\\docs\\\\test.ppt)，以及指定文件下载路径(例:D:\\Projects\\docs\\myDoc.pptx),'+
    '以及需要替换的文本和要替换成的文本，注:文件格式可为ppt或pptx都可,文件路径/和\的用法。<br/><br>第二：支持文件上传功能，选择上传要修改的ppt文件，指定修改内容。');

const page = ref('');
let pptDto1 = reactive({
    "sourceFileUrl": "",
    "targetFileUrl": "",
    "replaceList":[],
    "pages":[]
});
const dynamicValidateForm = reactive({
    domains: [
        {key: 1,willReplace: '',replaced: ''},
    ]
})

const removeDomain = (item) => {
    const index = dynamicValidateForm.domains.indexOf(item)
    if (index !== -1) {
        dynamicValidateForm.domains.splice(index, 1)
    }
}

const addDomain = () => {
    dynamicValidateForm.domains.push({
        key: Date.now(),
        willReplace: '',
        replaced: ''
    })
}

const submitForm = (formEl) => {
    //检查参数
    checkParam();
    $http.post(`${gatewayPrefix}/${baseDictServer}/file/updatePPTContent`,pptDto1).then(res=>{
        if(res){
            ElMessage.success("修改成功");
        }else{
            ElMessage.error('修改失败');
        }
    })
}

const checkParam = ()=>{
    if(dynamicValidateForm.domains.length === 0){
        return ElMessage.error('替换文本内容不能为空,请输入')
    }
    let flag = false
    dynamicValidateForm.domains.forEach(item =>{
        if(item.willReplace === ''){
            flag = true;
            return ElMessage.error('要替换的文本内容不能为空,请输入')
        }
        if(item.replaced === ''){
            flag = true;
            return ElMessage.error('替换后的文本内容不能为空,请输入')
        }
    })
    if(flag){
        return;
    }
    if(page.value !== '' && page.value !== undefined){
        pptDto1.pages = []
        try{
            let pageArr = page.value.split(',');
            pageArr.forEach(page =>{
                console.log(page);
                let reg = /^\+?[1-9][0-9]*$/;
                if(!reg.test(page)){
                    throw 'PagePatternException';
                }
                pptDto1.pages.push(page);
            })
        }catch(e){
            if(e === 'PagePatternException'){
                flag = true;
                ElMessage.error('替换的页码格式不正确，必须是正整数');
            }
        }
    }else{
        pptDto1.pages = []
    }
    if(flag){
        return;
    }
    pptDto1.replaceList = [];
    dynamicValidateForm.domains.forEach(item =>{
        var obj = {}
        obj.willReplace = item.willReplace
        obj.replaced = item.replaced
        pptDto1.replaceList.push(obj);
    })
}

const resetForm = (formEl) => {
    pptDto1.sourceFileUrl = '';
    pptDto1.targetFileUrl = '';
    pptDto1.replaceList = [];
    pptDto1.pages = [];
    page.value = ''
    dynamicValidateForm.domains = [];
    dynamicValidateForm.domains[0] = {key: 1,willReplace: '',replaced: ''};
}
// 方式2上传
const upload = ref()
const fileObj = ref()

//当超出限制时，执行的钩子函数
const handleExceed = (files) => {
    console.log("文件111==》",files);
    upload.value.clearFiles()
    const file = files[0]
    console.log("wenjian12==>", file);
    file.uid = genFileId()
    upload.value.handleStart(file)
}
let uploadUseNot = '使用第二种上传文件方式，和第一种区别不大，不用自己写原文件路径，上传即可，但是下载新文件路径以及替换页码和替换文本都需要填写，'+
                   '上传文件后，其他信息依旧在第一种方式中填写，只不过不用再写文件所在地址，填完之后点击第二种方式下的提交按钮即可。';
const uploadWayUseNotice = ()=>{
    ElMessageBox.alert(uploadUseNot, '上传使用说明', {
    autofocus: false,
    confirmButtonText: 'OK',
    callback: (action) => {}
  })
}

const beforeDocUpload = (docObj)=>{
    fileObj.value = docObj;
}

const submitUpload = () => {
    checkParam();
    //必须要提交，不然读不到file
    upload.value.submit()
    let fd = new FormData();
    fd.append("file",fileObj.value);
    fd.append('pptDto',JSON.stringify(pptDto1));
    $http.post(`${gatewayPrefix}/${baseDictServer}/file/updatePPTContentByFile`,fd).then(res=>{
        // if(res){
        //     ElMessage.success("修改成功");
        // }else{
        //     ElMessage.error('修改失败');
        // }
    })
    
}

</script>

<style lang="less" scoped>
.ppt-box{
    width: 100%;
    height: 100%;
    .top{
        width: 100%;
        height: 2%;
    }
    .c-box{
        width: 100%;
        height: 95%;
        overflow-y: scroll;
        margin-top: 20px;
        /deep/ .el-alert__title{
            font-size: 20px;
        }
        /deep/ .el-alert__description{
            font-size: 16px;
        }

        .up-1{
            margin-top: 10px;
            .demo-ruleForm{
                margin-top: 10px;
                .el-input{
                    width: 77%;
                }
            }
        }
        .up-2{
            .upload-demo{
                margin-left: 10%;
                margin-top: 20px;
            }
        }
        .up-3{
            margin-top: 20px;
        }
        .up-4{
            margin-top: 20px;
        }
    }
}
</style>